import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.select import Select


class Base():
    def __init__(self,driver):
        self.driver = driver
    def open_url(self,url):
        self.driver.get(url)
    # 定位元素的方法
    def find_element(self,loc):
        try:
            WebDriverWait(self.driver,20,0.5).until(lambda driver:driver.find_element(*loc).is_displayed())
            return self.driver.find_element(*loc)
        except Exception as e:
            self.driver.save_screenshot(time.strftime('%Y%m%d%H%M%S')+'.png')
            print(e)
    # 封装点击方法
    def click(self,loc):
        self.find_element(loc).click()
    # 封装输入的方法
    def send_keys(self,loc,info):
        self.find_element(loc).send_keys(info)
    # 封装强制等待的方法
    def sleep(self,x):
        time.sleep(x)
    #封装显示等待的方法
    def wait(self,x):
        self.driver.implicitly_wait(x)
    #封装滚动条的方法
    def window_scrollTo(self,x):
        self.driver.execute_script(f'window.scrollTo(0,{x})')
    # 封装弹窗
    def alert(self):
        self.driver.switch_to.alert.accept()
    # 封装ifram
    def ifram(self,loc):
        self.driver.switch_to.frame(self.find_element(loc))
    # 封装切换页面
    def window_handles(self):
        self.driver.switch_to.window(self.driver.window_handles[-1])
    # 鼠标单击
    def action_click(self,loc):
        ActionChains(self.driver).click(self.find_element(loc)).perform()
    # 鼠标双击
    def action_double_click(self,loc):
        ActionChains(self.driver).double_click(self.find_element(loc)).perform()
    # 键盘回车
    def keys_ENTER(self,loc):
        self.find_element(loc).send_keys(Keys.ENTER)
    # 键盘ctrl
    def keys_ctrl(self,loc):
        self.find_element(loc).send_key(Keys.CONTROL)
    # 回退
    def back(self):
        self.driver.back()
    # 刷新
    def refresh(self):
        self.driver.refresh()
    # 前进
    def forward(self):
        self.driver.forward()
    # 下拉框
    def select(self,loc,x):
        Select(self.find_element(loc)).select_by_index(x)
    def dy(self,loc):
        dy = self.find_element(loc)
        return dy.text


